package com.dfe.backend.common.runnur;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dfe.backend.entity.DfeFile;
import com.dfe.backend.service.DfeFileService;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.experimental.NonFinal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * 【描述】：预加载配置
 *
 * @author LiChang
 * @since 2025-8-8 9:11
 */
@Slf4j
@Component
@RequiredArgsConstructor
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
public class PreLoadConfigRunner implements ApplicationRunner {

    DfeFileService dfeFileService;

    @NonFinal
    @Value("${config.filePath.scd}")
    String scdPath;

    @NonFinal
    @Value("${config.filePath.spd}")
    String spdPath;

    @Override
    public void run(ApplicationArguments args) {
        log.info("==========================预加载开始==========================");
        // SCD/SPD文件读取
        preloadScdFile();
        preloadSpdFile();
        log.info("==========================预加载完成==========================");
    }


    /**
     * 【描述】: 预加载SCD文件配置
     *
     * @author LiChang
     * @since 2025-8-8 9:16
     */
    public void preloadScdFile() {
        if (StrUtil.isNotEmpty(scdPath)) {
            dfeFileService.analyseFile(scdPath, "scd");
        } else {
            // SCD文件读取
            DfeFile scdFile = dfeFileService.getOne(new QueryWrapper<DfeFile>().eq("file_type", "scd"));
            if (scdFile != null) {
                dfeFileService.analyseFile(scdFile.getFileUrl(), "scd");
            }
        }
    }

    /**
     * 【描述】: 预加载SPD文件配置
     *
     * @author LiChang
     * @since 2025-8-8 9:16
     */
    public void preloadSpdFile() {
        if (StrUtil.isNotEmpty(spdPath)) {
            dfeFileService.analyseFile(spdPath, "spd");
        } else {
            // SPD文件读取
            DfeFile spdFile = dfeFileService.getOne(new QueryWrapper<DfeFile>().eq("file_type", "spd"));
            if (spdFile != null) {
                dfeFileService.analyseFile(spdFile.getFileUrl(), "spd");
            }
        }
    }

}
